package org.goldfish.message_board01.servlets;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import org.goldfish.message_board01.services.UserService;

public class RegistrationServlet extends GFAbstractServlet {
    UserService service;

    @Override
    public void init() throws ServletException {
        service = new UserService();
        addService(service);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("register.jsp").forward(req, resp);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");

        if (name == null || name.isEmpty() || password == null || password.isEmpty()) {
            request.setAttribute("error", "Username and password cannot be empty.");
            RequestDispatcher dispatcher = request.getRequestDispatcher("register.jsp");
            dispatcher.forward(request, response);
            return;
        }

        if (service.register(name, password)) {
            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("error", "User registration failed.");
            RequestDispatcher dispatcher = request.getRequestDispatcher("register.jsp");
            dispatcher.forward(request, response);
        }
    }
}
